package com.qxy.practice.concurrent;

import com.google.common.util.concurrent.RateLimiter;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class RateLimitExample {

    // 创建一个 RateLimiter，设置每秒生成 2 个令牌（速率不足）
    private static final RateLimiter rateLimiter = RateLimiter.create(2.0);

    public static void main(String[] args) {
        long startTime = System.currentTimeMillis(); // 记录程序启动时间

        ExecutorService executor = Executors.newFixedThreadPool(5);

        // 每个线程处理 5 次请求，总共有 25 次请求
        for (int i = 0; i < 5; i++) {
            executor.submit(() -> {
                for (int j = 0; j < 5; j++) {
                    // 尝试获取令牌，阻塞直到有令牌可用
                    rateLimiter.acquire();

                    // 计算当前请求的耗时（秒）
                    long currentTime = System.currentTimeMillis();
                    long elapsedSeconds = (currentTime - startTime) / 1000;

                    System.out.println(
                            "Thread " + Thread.currentThread().getId() +
                                    " processed request " + j +
                                    " at " + elapsedSeconds + " seconds"
                    );
                }
            });
        }

        // 关闭线程池并等待所有任务完成
        executor.shutdown();
        try {
            executor.awaitTermination(1, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 输出总耗时（秒）
        long totalTime = (System.currentTimeMillis() - startTime) / 1000;
        System.out.println("Total time taken: " + totalTime + " seconds");
    }
}